package com.dragee.modules.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragee.common.core.domain.AjaxResult;
import com.dragee.config.BeautyConfig;
import com.dragee.constants.AuthConstants;
import com.dragee.modules.sys.entity.LoginUser;
import com.dragee.modules.sys.entity.SysRole;
import com.dragee.modules.sys.entity.SysUser;
import com.dragee.modules.sys.entity.UserEntity;
import com.dragee.modules.sys.service.ISysRoleService;
import com.dragee.modules.sys.service.UserService;
import com.dragee.utils.LoginUserUtil;
import com.dragee.utils.StringUtils;
import com.dragee.utils.UploadUtil;
import com.dragee.utils.file.FileUploadUtils;
import com.dragee.utils.file.MimeTypeUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 个人信息 业务处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{
    @Autowired
    private UserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Value("${webull.mapUploadPath}")
    private String rootPath;


    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        UserEntity user = userService.getById(loginUser.getUserId());
        List<Long> longs = roleService.selectRoleListByUserId(loginUser.getUserId());
        List<String> list = new ArrayList<>();
        for (Long aLong : longs) {
            QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id",aLong);
            String roleName = roleService.getOne(wrapper).getRoleName();

            list.add(roleName);
        }
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", list);

        return ajax;
    }

    /**
     * 修改用户
     */

    @PutMapping
    public AjaxResult updateProfile(@RequestBody UserEntity user)
    {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        user.setUsername(loginUser.getUsername());
        if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        user.setUserId(loginUser.getUserId());
        userService.saveOrUpdate(user);

            return success();

    }

    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        String password = new Sha256Hash(oldPassword, AuthConstants.SLAT_PWD).toHex();
        String passwordNew = new Sha256Hash(newPassword, AuthConstants.SLAT_PWD).toHex();
        if (!password.equals(loginUser.getPassword()))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (passwordNew.equals(oldPassword))
        {
            return error("新密码不能与旧密码相同");
        }
            UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("userId",loginUser.getUserId()));
            user.setPassword(passwordNew);
            userService.saveOrUpdate(user);
            return success();

    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
//        if (!file.isEmpty()) {
//            String fileName = file.getOriginalFilename();
//            String dirPath = rootPath + "//avatarfile";
//            String filePath = dirPath + "//" + fileName;
//            UploadUtil.onlyUpload(file, dirPath);
//
//            Long loginUserId = LoginUserUtil.getLoginUserId();
//            UserEntity user = userService.getById(loginUserId);
//            user.setAvatar("/work/file"+filePath);
//            userService.saveOrUpdate(user);
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", "/work/file"+filePath);
//                return ajax;
//            }else {
//            return error("上传图片异常，请联系管理员");
//        }
        if (!file.isEmpty())
        {
            LoginUser loginUser = LoginUserUtil.getLoginUser();
            String avatar = FileUploadUtils.upload(BeautyConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            Long loginUserId = LoginUserUtil.getLoginUserId();
            UserEntity user = userService.getById(loginUserId);
            user.setAvatar(avatar);
            userService.saveOrUpdate(user);
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                return ajax;
            }
        return error("上传图片异常，请联系管理员");
        }


}